import java.util.concurrent.locks.ReentrantLock;

public class Lock_Fair {
    private static final ReentrantLock lock = new ReentrantLock(true); //设置为公平锁
    public static void main(String[] args) {
        new Thread(()->getLock(),"线程1").start();
        new Thread(()->getLock(),"线程2").start();
        new Thread(()->getLock(),"线程3").start();

    }

    public static void getLock(){
        for (int i = 0; i < 2; i++) {
            try {
                lock.lock();
                System.out.println(Thread.currentThread().getName()+"获取了锁。");
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }
    }
}



